//
//  UIColor.swift
//  CXBaseUtil
//
//  Created by 李旭峰 on 2021/2/26.
//

import Foundation
import UIKit

public extension UIColor {
  
    func add(color: UIColor, blendModel: CGBlendMode) -> UIColor? {
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    var pixel = Array<UInt8>(repeating: 0, count: 4)
    guard let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) else {
      return nil
    }
    context.setFillColor(cgColor)
    context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
    context.setBlendMode(blendModel)
    context.setFillColor(color.cgColor)
    context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
    return UIColor(red: CGFloat(pixel[0]) / 255.0, green: CGFloat(pixel[1]) / 255.0, blue: CGFloat(pixel[2]) / 255.0, alpha: CGFloat(pixel[3]) / 255.0)
  }
}

public extension UIColor {
  
  /**
   16进制表示颜色
   
   - parameter hex:
   
   - returns:
   */
    convenience init(hex: UInt, alpha: CGFloat = 1.0) {
    self.init(red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
              green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
              blue: CGFloat(hex & 0x0000FF) / 255.0,
              alpha: alpha)
  }
  
}

// MARK: - 全局方法
public extension UIColor {
  
  /**
   把颜色转为图片对象
   
   - parameter color:
   
   - returns:
   */
    class func imageWithColor(color: UIColor) -> UIImage{
    //        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size);
    let context = UIGraphicsGetCurrentContext();
    
    context!.setFillColor(color.cgColor);
    context!.fill(rect);
    
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image!;
  }
  
  /**
   把颜色转为图片对象
   
   - parameter color:
   
   - returns:
   */
    class func imageWithColor(color: UIColor,rect:CGRect) -> UIImage{
    //        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    UIGraphicsBeginImageContext(rect.size);
    let context = UIGraphicsGetCurrentContext();
    
    context!.setFillColor(color.cgColor);
    context!.fill(rect);
    
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image!;
  }
}
public extension UIColor {
  
  /**
   16进制表示颜色
   
   - parameter hex:
   
   - returns:
   */
   class func ch_hex(_ hex: UInt, alpha: Float = 1.0) -> UIColor {
    return UIColor(red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
                   green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
                   blue: CGFloat(hex & 0x0000FF) / 255.0,
                   alpha: CGFloat(alpha))
  }
  
}
public extension UIColor {
    static func colorFromCode(_ code: Int) -> UIColor {
    let red = CGFloat(((code & 0xFF0000) >> 16)) / 255
    let green = CGFloat(((code & 0xFF00) >> 8)) / 255
    let blue = CGFloat((code & 0xFF)) / 255
    
    return UIColor(red: red, green: green, blue: blue, alpha: 1)
  }
}
public extension UIColor {
  
  class var pink: UIColor {
    return UIColor(red: 255.0 / 255.0, green: 192.0 / 255.0, blue: 203.0 / 255.0, alpha: 1)
  }
  class var random: UIColor {
    let red   = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 255.0)
    let green = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 255.0)
    let blue  = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 255.0)
    return UIColor(red: red, green: green, blue: blue, alpha: 1)
  }
  class func color(withHexLiteral hexColor: Int) -> UIColor? {
    return UIColor(hexLiteral: hexColor)
  }
  convenience init(hexLiteral: Int) {
    let red   = CGFloat((hexLiteral >> 16) & 0xFF) / 255.0
    let green = CGFloat((hexLiteral >> 08) & 0xFF) / 255.0
    let blue  = CGFloat((hexLiteral >> 00) & 0xFF) / 255.0
    self.init(red: red, green: green, blue: blue, alpha: 1)
  }
  
  /**
   支持0x、#开头的6位或8位(alpha)的字符串转换为颜色
   如果不为6位或8位，小于6位，前面补0至6位。小于8位，前面补0至8位
   
   - parameter hexString: 十六进制字符串
   
   - returns: UIColor
   */
  convenience init?(hexString: String?) {
    
    guard var hex = hexString else {
      return nil
    }
    
    func hex2dec(_ num:String) -> Float {
      let str = num.uppercased()
      var sum:Float = 0
      for i in str.utf8 {
        sum = sum * 16 + Float(i) - 48 // 0-9 从48开始
        if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
          sum -= 7
        }
      }
      return sum
    }
    hex = hex.replacingOccurrences(of: "0x", with: "")
    hex = hex.replacingOccurrences(of: "#", with: "")
    if hex.count > 8 {
      hex = String(hex.prefix(hex.count - 8))
    }
    
    let count = hex.count
    
    let count0 = ((count == 6 || count == 8) ? 0 : (count < 6 ? 6 - count : (count < 8 ? 8 - count : 0)))
    
    hex = String.init(repeating: "0", count: count0) + hex
    
    let containAlpha = hex.count == 8
    
    let alpha = hex.index(hex.startIndex, offsetBy: 0)
    let red = hex.index(hex.startIndex, offsetBy: containAlpha ? 2 : 0)
    let green = hex.index(red, offsetBy: 2)
    let blue = hex.index(green, offsetBy: 2)
    
    let alphaStr: String = String(hex[alpha..<(hex.index(alpha, offsetBy: 2))])
    let redStr = String(hex[red..<(hex.index(red, offsetBy: 2))])
    let greenStr = String(hex[green..<(hex.index(green, offsetBy: 2))])
    let blueStr = String(hex[blue..<(hex.index(blue, offsetBy: 2))])
    
    self.init(red:CGFloat(hex2dec(redStr))/255.0,
              green:CGFloat(hex2dec(greenStr)) / 255.0,
              blue:CGFloat(hex2dec(blueStr)) / 255.0,
              alpha: containAlpha ? CGFloat(hex2dec(alphaStr)) / 255.0 : 1)
    
  }
  
  class func colorWithHexString (_ hexString:String?)-> UIColor? {
    
    return UIColor.init(hexString: hexString)
  }
  
}


public extension UIColor {
  
    convenience init(hex: Int, alpha: CGFloat) {
    self.init(red: (CGFloat((hex & 0xff0000) >> 16) / 255.0), green: CGFloat((hex & 0xff00) >> 8) / 255.0, blue: CGFloat(hex & 0xff)/255.0, alpha: alpha)
  }
  
    convenience init(hex: Int) {
    self.init(hex: hex, alpha: 1.0)
  }
  
    convenience init(hexStr: String, alpha: CGFloat) {
    var hex = hexStr
    if hex.hasPrefix("#") {
      let startIndex: String.Index = hex.startIndex
      let endIndex: String.Index = hex.index(startIndex, offsetBy: 1)
      hex.removeSubrange(startIndex..<endIndex)
    }
    if hex.count != 6 {
      self.init(white: 0, alpha: alpha)
      return
    }
    let scan = Scanner(string: hex)
    var hexInt : UInt32 = 0
    scan.scanHexInt32(&hexInt)
    self.init(hex: Int(hexInt), alpha: alpha)
  }
  
    convenience init(hexStr: String) {
    if hexStr.count == 7 {
      self.init(hexStr: hexStr, alpha: 1.0)
    }else{
      self.init(alphaHexStr: hexStr)
    }
    //        self.init(hexStr: hexStr, alpha: 1.0)
  }
    convenience init(alphaHexStr: String){
    var totalHex = alphaHexStr
    if totalHex.hasPrefix("#") {
      let startIndex: String.Index = totalHex.startIndex
      let endIndex: String.Index = totalHex.index(startIndex, offsetBy: 1)
      totalHex.removeSubrange(startIndex..<endIndex)
    }
    if totalHex.count != 8 {
      self.init(white: 0, alpha: 1.0)
      return
    }
    let alphaStartIndex = totalHex.startIndex
    let alphaEndIndex = totalHex.index(alphaStartIndex, offsetBy: 2)
    let alpha = totalHex[alphaStartIndex..<alphaEndIndex]
    let hexStartIndex = totalHex.index(alphaStartIndex, offsetBy: 2)
    let hexEndIndex = totalHex.index(alphaStartIndex, offsetBy: 8)
    let hex = totalHex[hexStartIndex..<hexEndIndex]
    
    let alphaScan = Scanner(string: String(alpha))
    var alphaInt:UInt32 = 0
    alphaScan.scanHexInt32(&alphaInt)
    let alphaValue = Double(alphaInt)/255.0
    let hexScan = Scanner(string: String(hex))
    var hexInt:UInt32 = 0
    hexScan.scanHexInt32(&hexInt)
    let hexValue = Int(hexInt)
    self.init(hex: hexValue, alpha: CGFloat(alphaValue))
  }
    func rgb(_ r: CGFloat,_ g: CGFloat,_ b: CGFloat) -> UIColor {
    return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
  }
  ///不需要除以255.0
    convenience init(_ r: CGFloat,_ g: CGFloat,_ b: CGFloat) {
    self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
  }
}
